package com.lang.generator.controller;

import cn.hutool.core.io.IoUtil;
import cn.lang.global.ret.Ret;
import cn.lang.global.validator.ValidatorUtil;
import com.lang.generator.domain.dto.ContentDto;
import com.lang.generator.domain.vo.GeneratorVo;
import com.lang.generator.domain.vo.MockDataVo;
import com.lang.generator.service.GeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 生成器控制器
 *
 * @author Lang
 * @date 2022/11/19
 */
@Api(tags = "生成器控制器")
@Slf4j
@RestController
@RequestMapping("/generator")
public class GeneratorController {
    @Resource
    private GeneratorService generatorService;

    /**
     * 导出代码
     *
     * @param generatorVo generatorVo
     * @param response    response
     * @throws IOException IOException
     */
    @ApiOperation(value = "代码生成--ZIP包形式")
    @PostMapping("/zip")
    public void generatorCodeZip(@RequestBody GeneratorVo generatorVo, HttpServletResponse response) throws IOException {
        log.info("test");
        List<ContentDto> contentDtoList = generatorService.generatorCode(generatorVo);
        byte[] data = generatorService.packageCodeZip(contentDtoList);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write(response.getOutputStream(), false, data);
    }

    @ApiOperation(value = "代码生成--文本形式")
    @PostMapping("/text")
    public Ret<List<ContentDto>> generatorCodeText(@RequestBody GeneratorVo generatorVo) {
        List<ContentDto> contentDtoList = generatorService.generatorCode(generatorVo);
        return Ret.success(contentDtoList);
    }


    /**
     * 生成模拟数据insert sql语句
     *
     * @param mockDataVo mockDataVo
     * @return Ret
     */
    @ApiOperation(value = "生成模拟数据insert sql语句")
    @PostMapping("/mockSql")
    public Ret<String> generatorMockSql(@RequestBody MockDataVo mockDataVo) {

        ValidatorUtil.validate(mockDataVo);
        String sql = generatorService.generatorMockSql(mockDataVo.getTableStructure(), mockDataVo.getRowNum());
        return Ret.success(sql);
    }


}
